<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="活动名称" prop="actName">
        <el-input v-model="queryParams.actName" placeholder="请输入活动名称" clearable size="small"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="参与者" prop="awardGroupDesc">
        <el-input v-model="queryParams.awardGroupDesc" placeholder="请输入参与者" clearable size="small"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="奖励任务" prop="awardConfigDesc">
        <el-input v-model="queryParams.awardConfigDesc" placeholder="请输入奖励任务" clearable size="small"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="活动有效期" prop="activityTime">
        <el-date-picker clearable size="small" v-model="queryParams.startTime" type="date"
          value-format="yyyy-MM-dd HH:mm:ss" placeholder="请选择开始时间">
        </el-date-picker>
        <el-date-picker clearable size="small" v-model="queryParams.endTime" type="date"
          value-format="yyyy-MM-dd HH:mm:ss" placeholder="请选择结束时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['bizsys:activity:add']">新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['bizsys:activity:remove']">删除</el-button>
      </el-col> -->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="activityList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="#" align="center" prop="id" width="60" />
      <el-table-column label="活动名称" align="center" prop="actName" />
      <el-table-column label="活动类型" align="center" prop="actType" :formatter="actTypeFormatter" />
      <el-table-column label="参与者" align="center" prop="awardGroupDesc" show-overflow-tooltip width="180" />
      <el-table-column label="奖励任务" align="center" show-overflow-tooltip width="180"
        class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="handleAwardTaskList(scope.row)"
            v-hasPermi="['bizsys:activity:search']">{{scope.row.awardConfigDesc}}</el-button>
        </template>
      </el-table-column>
      <el-table-column label="活动开始日期" align="center" prop="startTime" width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="活动结束日期" align="center" prop="endTime" width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="state" :formatter="stateFormat" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['bizsys:activity:edit']">修改</el-button>
          <!-- <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['bizsys:activity:remove']">删除</el-button> -->
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleStartAndStop(scope.row)"
            v-hasPermi="['bizsys:activity:edit']">{{scope.row.state==='1'?'停用':'启用'}}</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改奖励活动对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="580px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="活动名称" prop="actName">
          <el-input v-model="form.actName" placeholder="请输入活动名称" />
        </el-form-item>
        <el-form-item label="活动类型" prop="actType">
          <el-select v-model="form.actType" placeholder="请选择活动类型" clearable size="small">
            <el-option v-for="dict in actTypeOptions" :key="dict.dictValue" :label="dict.dictLabel"
              :value="dict.dictValue" />
          </el-select>
        </el-form-item>
        <el-form-item label="活动有效期" prop="startTime">
          <el-date-picker clearable size="small" v-model="form.startTime" type="date" value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择开始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item prop="endTime">
          <el-date-picker clearable size="small" v-model="form.endTime" type="date" value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择结束时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="参与条件" prop="actCondition">
          <el-radio-group v-model="form.actCondition">
            <el-radio @change="actConditionSelect" v-for="dict in actCondictionOptions" :key="dict.dictValue"
              :label="dict.dictValue">{{dict.dictLabel}}
            </el-radio>
          </el-radio-group>
          <el-form-item v-show="lableSelectShow" prop="awardGroupId">
            <el-tag type="success" v-for="desc in awardGroupSelect.awardGroupDesc">{{desc}}</el-tag>
            <el-button class="lable-select-btn" size="mini" type="text" icon="el-icon-edit"
              @click="handleAwardGroupList()" v-hasPermi="['bizsys:activity:edit']">选择标签组</el-button>
          </el-form-item>
        </el-form-item>
        <el-form-item label="选择分销" prop="distributionRatioId">
          <el-select @focus="getRatioList" v-model="form.distributionRatioId" placeholder="请选择分销" clearable
            size="small">
            <el-option v-for="dict in distributionRatioOptions" :key="dict.id" :label="dict.name" :value="dict.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="奖励任务" prop="awardConfigId">
          <el-tag type="success" v-for="desc in awardConfigSelect.awardConfigDesc">{{desc}}</el-tag>
          <el-button class="lable-select-btn" size="mini" type="text" icon="el-icon-edit"
            @click="handleAwardConfigSelect()" v-hasPermi="['bizsys:activity:edit']">选择奖励任务</el-button>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 奖励活动列表显示 -->
    <el-dialog :title="awardConfig.title" :visible.sync="awardConfig.open" width="1000px" append-to-body>
      <div class="app-container">
        <el-table v-loading="loading" :data="awardConfig.awardConfigList">
          <el-table-column label="任务编号" align="center" prop="code" />
          <el-table-column label="任务要求" align="center" prop="awardEventType" :formatter="awardEventTypeFormat" />
          <el-table-column label="奖励次数" align="center" prop="awardNum" />
          <el-table-column label="奖励内容" align="center" prop="awardContent" :formatter="awardContentFormat" />
          <el-table-column label="奖励方式" align="center" prop="awardMethod" :formatter="awardMethodFormat" />
        </el-table>
      </div>
    </el-dialog>

    <!-- 选择标签组列表 -->
    <el-dialog :title="awardGroupSelect.title" :visible.sync="awardGroupSelect.open" width="1000px" append-to-body>
      <div class="app-container">
        <el-table ref="multipleTable" v-loading="loading" :data="awardGroupSelect.awardGroupSelectList"
          @selection-change="handleLabelSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="分组标签名称" align="center" prop="groupName" />
        </el-table>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitLabelSelect">确 定</el-button>
        <el-button @click="cancelLabelSelect">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 选择奖励任务列表 -->
    <el-dialog :title="awardConfigSelect.title" :visible.sync="awardConfigSelect.open" width="1000px" append-to-body>
      <div class="app-container">
        <el-table ref="multipleTable" v-loading="loading" :data="awardConfigSelect.awardConfigSelectList"
          @selection-change="handleConfigSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="任务编号" align="center" prop="code" />
          <el-table-column label="任务要求" align="center" prop="awardEventType" :formatter="awardEventTypeFormat" />
          <el-table-column label="奖励次数" align="center" prop="awardNum" />
          <el-table-column label="奖励内容" align="center" prop="awardContent" :formatter="awardContentFormat" />
          <el-table-column label="奖励方式" align="center" prop="awardMethod" :formatter="awardMethodFormat" />
          <el-table-column label="奖励数值" align="center" prop="awardValue" />
        </el-table>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitConfigSelect">确 定</el-button>
        <el-button @click="cancelConfigSelect">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    listActivity,
    getActivity,
    delActivity,
    addActivity,
    updateActivity,
    exportActivity,
    startAndStop
  } from "@/api/bizsys/award_activity";
  import {
    listConfig,
  } from "@/api/bizsys/award_config";
  import {
    listGroup,
  } from "@/api/bizsys/award_group";
  import {
    listRatio,
  } from "@/api/bizsys/award_distribution_ratio"

  export default {
    name: "Activity",
    components: {},
    data() {
      return {
        awardGroupSelect: {
          title: '选择分组标签',
          open: false,
          total: 0,
          awardGroupList: [],
          awardGroupDesc: [],
          labelSelection: [],
        },
        awardConfigSelect: {
          title: '选择奖励任务',
          open: false,
          total: 0,
          configSelection:[],
          awardConfigSelectList: [],
          awardConfigDesc: [],
        },
        awardConfig: {
          title: '奖励任务',
          open: false,
          total: 0,
          awardConfigList: [],
          // 选中数组
          ids: [],
        },
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        //标签选择按钮显示
        lableSelectShow: false,
        //可选择的分销配置
        distributionRatioOptions: [],
        //活动类型
        actTypeOptions: [],
        //活动参与条件
        actCondictionOptions: [],
        //状态
        stateOptions: [],
        // 遮罩层
        loading: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 奖励活动表格数据
        activityList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          actName: null,
          awardGroupDesc: null,
          awardConfigDesc: null,
          startTime: null,
          endTime: null,
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          actName: [{
            required: true,
            message: "活动名称不能为空",
            trigger: "blur"
          }],
          actType: [{
            required: true,
            message: "活动类型不能为空",
            trigger: "blur"
          }],
          startTime: [{
            required: true,
            message: "活动有效期不能为空",
            trigger: "blur"
          }],
          endTime: [{
            required: true,
            message: "活动有效期不能为空",
            trigger: "blur"
          }],
          actCondition: [{
            required: true,
            message: "参与条件不能为空",
            trigger: "blur"
          }],
          distributionRatioId: [{
            required: true,
            message: "分销配置不能为空",
            trigger: "blur"
          }],
          awardConfigId: [{
            required: true,
            message: "奖励配置不能为空",
            trigger: "blur"
          }],
        }
      };
    },
    created() {
      //活动列表字典
      this.getDicts("award_act_type").then(response => {
        this.actTypeOptions = response.data;
      });
      this.getDicts("award_act_condiction").then(response => {
        this.actCondictionOptions = response.data;
      });
      this.getDicts("state").then(response => {
        this.stateOptions = response.data;
      });
      //奖励配置列表
      this.getDicts("award_event_type").then(response => {
        this.awardEventTypeOptions = response.data;
      });
      this.getDicts("award_method").then(response => {
        this.awardMethodOptions = response.data;
      });
      this.getDicts("award_content").then(response => {
        this.awardContentOptions = response.data;
      });
      //分销选项
      this.getRatioList();
    },
    mounted() {
      //活动列表
      this.getList();
    },
    methods: {
      //选择参与者触发
      actConditionSelect(value) {
        if (value == 0) {
          this.lableSelectShow = false;
          this.rules.awardGroupId = [{
            required: false,
            message: "标签分组不能为空",
            trigger: "blur"
          }]
          return;
        }
        this.lableSelectShow = true;
        this.rules.awardGroupId = [{
          required: true,
          message: "标签分组不能为空",
          trigger: "blur"
        }]
      },
      //打开奖励任务选择
      handleAwardConfigSelect() {
        this.awardConfigSelect.open = true;
        this.getAwardConfigSelectList();
      },
      //打开选择标签组列表
      handleAwardGroupList() {
        this.awardGroupSelect.open = true;
        this.getAwardGroupList();
      },
      //打开奖励任务列表
      handleAwardTaskList(row) {
        this.awardConfig.open = true;
        this.getAwardConfigList(row);
      },
      // 活动类型字典翻译
      actTypeFormatter(row, column) {
        return this.selectDictLabel(this.actTypeOptions, row.actType);
      },
      // 状态字典翻译
      stateFormat(row, column) {
        return this.selectDictLabel(this.stateOptions, row.state);
      },
      // 奖励要求字典翻译
      awardEventTypeFormat(row, column) {
        return this.selectDictLabel(this.awardEventTypeOptions, row.awardEventType);
      },
      // 奖励方式字典翻译
      awardMethodFormat(row, column) {
        return this.selectDictLabel(this.awardMethodOptions, row.awardMethod);
      },
      // 奖励内容字典翻译
      awardContentFormat(row, column) {
        return this.selectDictLabel(this.awardContentOptions, row.awardContent);
      },
      /** 查询奖励活动列表 */
      getList() {
        this.loading = true;
        listActivity(this.queryParams).then(response => {
          this.activityList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      /** 查询可选择的分销配置列表 */
      getRatioList() {
        this.loading = true;
        listRatio().then(response => {
          this.distributionRatioOptions = response.rows;
          this.loading = false;
        });
      },
      /** 查询可选择的标签分组列表  */
      getAwardGroupList(row) {
        this.loading = true;
        let _this = this;
        listGroup({
          "state": '1'
        }).then(response => {
          this.awardGroupSelect.awardGroupSelectList = response.rows;
          this.awardGroupSelect.total = response.total;
          this.loading = false;
          //根据数据选中
          this.ids = this.form.awardGroupId;
          this.awardGroupSelect.awardGroupSelectList.forEach(row => _this.$refs.multipleTable.toggleRowSelection(
            row));
        });
      },
      /** 查询奖励活动配置列表  */
      getAwardConfigSelectList(row) {
        this.loading = true;
        listConfig({
          "state": '1'
        }).then(response => {
          this.awardConfigSelect.awardConfigSelectList = response.rows;
          this.awardConfigSelect.total = response.total;
          this.loading = false;
        });
      },
      /** 查询奖励活动配置列表  */
      getAwardConfigList(row) {
        this.loading = true;
        listConfig({
          "ids": row.awardConfigId
        }).then(response => {
          this.awardConfig.awardConfigList = response.rows;
          this.awardConfig.total = response.total;
          this.loading = false;
        });
      },
      //取消选择奖励任务
      cancelConfigSelect() {
        this.awardConfigSelect.open = false;
      },
      // 取消选择标签
      cancelLabelSelect() {
        this.awardGroupSelect.open = false;
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: null,
          actName: null,
          actType: null,
          distributionRatioId: null,
          awardGroupId: null,
          awardConfigId: null,
          startTime: null,
          endTime: null,
          state: '0',
        };
        this.resetForm("form");
        this.awardConfigSelect.awardConfigDesc = [];
        this.awardGroupSelect.awardGroupDesc = [];
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 标签多选框选中数据
      handleLabelSelectionChange(selection) {
        this.awardGroupSelect.labelSelection = selection;
      },
      // 奖励任务多选框选中数据
      handleConfigSelectionChange(selection) {
        this.awardConfigSelect.configSelection = selection;
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加奖励活动";
      },
      /** 启用/停用 */
      handleStartAndStop(row) {
        let _this = this;
        let params = {};
        let optionMsg = '';
        params.id = row.id;
        if (row.state === '1') {
          params.state = '0';
          optionMsg = '停用';
        } else {
          params.state = '1';
          optionMsg = '启用';
        }
        this.$confirm('是否' + optionMsg + '活动"?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          startAndStop(params).then(response => {
            _this.getList();
          });
        }).then(() => {
          this.msgSuccess("操作成功");
        })
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        let _this = this;
        this.reset();
        const id = row.id || this.ids
        getActivity(id).then(response => {
          this.form = response.data;
          this.open = true;
          this.title = "修改奖励活动";
          console.info(JSON.stringify(this.form));
          //渲染一下标签
          this.awardGroupSelect.awardGroupDesc = this.form.awardGroupDesc.split(',')
          this.awardConfigSelect.awardConfigDesc = this.form.awardConfigDesc.split(',')
          //触发一次选择事件
          _this.actConditionSelect(this.form.actCondition);
        });
      },
      /** 提交奖励任务选择标签 */
      submitConfigSelect() {
        this.form.awardConfigId = this.awardConfigSelect.configSelection.map(item => item.id).join(",");
        this.awardConfigSelect.awardConfigDesc = this.awardConfigSelect.configSelection.map(item => this.awardEventTypeFormat(item, null));
        this.awardConfigSelect.open = false;
      },
      /** 提交选择标签 */
      submitLabelSelect() {
        this.form.awardGroupId = this.awardGroupSelect.labelSelection.map(item => item.id).join(",");
        this.awardGroupSelect.awardGroupDesc = this.awardGroupSelect.labelSelection.map(item => item.groupName);
        this.awardGroupSelect.open = false;
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.id != null) {
              updateActivity(this.form).then(response => {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addActivity(this.form).then(response => {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$confirm('是否确认删除奖励活动编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delActivity(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
      },
      /** 导出按钮操作 */
      handleExport() {
        const queryParams = this.queryParams;
        this.$confirm('是否确认导出所有奖励活动数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportActivity(queryParams);
        }).then(response => {
          this.download(response.msg);
        })
      }
    }
  };
</script>
<style>
  .lable-select-btn {
    color: #409EFF;
    margin-left: 10px;
  }
</style>
